// component/bind_phone/bind_phone.js
import grace from "../../utils/grace.js"
import config from "../../utils/config.js"
grace.component({
  properties: {
    
  },
  data: {
    isShow: false,
    timer: null,
    maxtime: 60,
    btnSend: '发送验证码',
    mobile: '',
    code: '',
    text: '',
    callback: null
  },
  methods: {
    //隐藏弹框
    hideDialog() {
      this.setData({
        isShow: false
      })
    },
    //展示弹框
    showDialog() {
      this.setData({
        isShow: true
      });
    },
    inputChange: function (e) {
      var value = e.detail.value;
      var item = e.target.dataset.item;
      this.$data[item] = value;
    },
    toast:function(msg){
      wx.showToast({
        icon: 'none',
        title: msg,
      })
    },
    doSubmit: function () {
      if (this.data.code.length == 0) {
        this.toast('请填写验证码！');
        return;
      }
      let that = this;
      let param = {
        mobile: this.data.mobile,
        code: this.data.code
      };
      that.$http.post('api/sms/verify', param).then((res) => {
        that.$http.post('api/user/binding_mobile', param).then((res) => {
          that.setData({
            isShow: false
          })
          that.$bus.$emit("update_phone_event");
          that.toast('绑定手机成功');
        });
      });
    },
    sendCode: function (e) {
      if (this.$data.timer != null) return;
      if (this.data.mobile.length == 0) {
        this.toast('请输入手机号码');
        return;
      }
      let params = {
        mobile: this.data.mobile,
        send_source: 'weixin',
        api_secret: config.apiSecret
      };
      let that = this;
      this.$http.post('api/sms/send_verify', params).then((res) => {
        that.toast('验证码发送成功');
        that.$data.timer = setInterval(function () {
          that.count_timer();
        }, 1000);
      });
    },
    count_timer: function (e) {
      if (this.$data.maxtime >= 0) {
        this.$data.btnSend = '等待' + this.$data.maxtime + 's';
        this.$data.maxtime = this.$data.maxtime - 1;
      } else {
        clearInterval(this.$data.timer);
        this.$data = {
          btnSend: '发送验证码',
          maxtime: 60,
          timer: null
        };
      }
    }
  }
})

